package com.todod.service;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.todod.common.util.MinIoUtils;
import com.todod.exception.UploadFileException;

/**
 * 附件service
 *
 */
@Service
@Transactional
public class FileinfoService {
	Logger log = LoggerFactory.getLogger(this.getClass());
	@Value("${file.upload.path}")
	private String uploadPath; // 文件路径
	@Value("${file.upload.mapping}")
	private String showPath; // 映射路径
	@Value("${file.visit}")
	private String visi;

	// 存储桶名称
	@Value("${minio.bucketName}")
	private String bucketName;
	@Autowired
	private MinIoUtils minIoUtils;

	/**
	 * 上传文件
	 * 
	 * @Title: saveUploadFile
	 * @Description:
	 * @author gsh
	 * @date 2019年8月12日
	 * @param request
	 * @return
	 * @return
	 */
	public String saveUploadFile(Long userId, HttpServletRequest request) {
		try {
//			String newDate = TododDate.getInstance().getSimpledate();
//
//			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
//			MultipartFile uploadFile = req.getFile("uploadfile_ant");
//
//			// 上传路径
//			String root = uploadPath;
//
//			String abstractPath = root + File.separator + "upload" + File.separator + newDate;
//
//			String rPath = showPath + "/" + "upload" + "/" + newDate;
//
//			File dir = new File(abstractPath);
//			if (!dir.exists()) {
//				dir.mkdirs();
//			}
//
//			String originalName = uploadFile.getOriginalFilename();
//			String suffix = StringUtils.substringAfterLast(originalName, ".");
//
//			String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
//			// 保存数据
//			FileCopyUtils.copy(uploadFile.getInputStream(),
//					new FileOutputStream(abstractPath + File.separator + fileName));

			String relativePath = null;

			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
			MultipartFile uploadFile = req.getFile("uploadfile_ant");// 返回上传文件的内容和描述

			relativePath = minIoUtils.upload(uploadFile, bucketName, null);

			return relativePath;

		} catch (Exception e) {
			log.error("file_upload", e);
			throw new UploadFileException("上传文件失败");
		}
	}

	public static void main(String[] args) {
		System.out.println(UUID.randomUUID().toString().replaceAll("-", ""));
	}

}
